<!-- src/view/user_book.vue -->
<template>
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 20px">
    <el-form-item label="书籍名">
      <el-input v-model="searchObj.book_name" placeholder="请输入书籍名称" clearable />
    </el-form-item>

    <el-form-item label="作者">
      <el-input v-model="searchObj.author" placeholder="请输入作者" clearable />
    </el-form-item>

    <el-form-item label="书籍类别">
      <el-input v-model="searchObj.category_name" placeholder="请输入书籍类别" clearable />
    </el-form-item>

    <el-form-item label="书架">
      <el-input v-model="searchObj.bookshelf_name" placeholder="请输入书架" clearable />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="书名" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.book_name }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="书架" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.bookshelf_name }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="出版社" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.publisher }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="作者" width="100">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.author }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="类别" width="80">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.category_name }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="国际书号" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.isbn }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="馆藏数量" width="80">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ scope.row.num }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="入库时间" width="180">
      <template #default="scope">
        <div style="display: flex; align-items: center">
          <span>{{ formatDate(scope.row.create_time) }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button
            type="primary"
            size="small"
            @click="handleBorrow(scope.row)"
            :disabled="scope.row.num <= 0"
        >
          借书
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!--分页-->
  <el-pagination
      style="margin-top:20px"
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<script setup>
import api from '../api/book_api.js'
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/request.js'

// 定义绑定的数据
const tableData = ref([])
const searchObj = ref({
  current: 1,
  limit: 10,
  book_name: '',
  bookshelf_name: '',
  publisher: '',
  author: '',
  isbn: '',
  num: '',
  detail: '',
  category_name: '',
})
const total = ref(0)
const currentUserId = ref(null)

// 获取当前用户ID
const getCurrentUserId = async () => {
  try {
    const response = await request({
      url: '/api/login/logininfo',
      method: 'get'
    })
    currentUserId.value = response.id
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const search = async () => {
  var result = await api.page(searchObj.value)
  tableData.value = result.data
  total.value = result.count
}

// 页面加载后要挂载的数据
onMounted(async () => {
  await getCurrentUserId()
  search()
})

// 定义方法
const handleSizeChange = () => {
  search()
}

const handleCurrentChange = () => {
  search()
}

const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 时间格式化函数
const formatDate = (dateString) => {
  if (!dateString) return ''

  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateString
  }
}

// 借书操作
const handleBorrow = (row) => {
  if (row.num <= 0) {
    ElMessage.warning('该书籍库存不足，无法借阅')
    return
  }

  ElMessageBox.confirm(
      `确认借阅书籍《${row.book_name}》吗？`,
      '借书确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const response = await request({
        url: '/api/borrow/borrow',
        method: 'post',
        params: {
          user_id: currentUserId.value,
          book_id: row.id
        }
      })
      // 更新书籍库存显示
      row.num = response.data.book_num
      search()
    } catch (error) {

    }
  }).catch(() => {
    // 用户取消操作
  })
}
</script>

<style scoped>
</style>
